/***************************************************************************
 *   Copyright (C) 2009 by Zheng Yonglei
 *   zhengyonglei@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "ExportDataDialog.h"
#include "Logger.h"
#include "Options.h"

ExportDataDialog::ExportDataDialog(QDialog *parent)
    : QDialog(parent)
{
	ui.setupUi(this);
	ui.saveFileNameEdit->setEnabled(false);

	QObject::connect(ui.closeButton, SIGNAL(clicked()), this, SLOT(accept()));
	QObject::connect(ui.saveColumnNameWidget, SIGNAL(itemClicked(QTreeWidgetItem*, int)),
			this, SLOT(itemClicked(QTreeWidgetItem*, int)));
	QObject::connect(ui.saveButton, SIGNAL(clicked()), this, SLOT(save()));
}

ExportDataDialog::~ExportDataDialog()
{

}

void ExportDataDialog::setExportColumnList()
{
	QString command;
	command = QString("SELECT name FROM sqlite_master WHERE type='table'");
	DB.quickGet(command);
	for (int i=0; i<DB.getRowCount(); i++)
	{
		QString tableName = DB.getTableValue(i, "name");
		if (tableName != QString("sqlite_sequence"))
		{
			QTreeWidgetItem* tableItem =
				new QTreeWidgetItem(ui.saveColumnNameWidget, QStringList(tableName));
			tableItem->setCheckState(0, Qt::Unchecked);
			mTableNames.push_back(tableName);
		}
	}

	for (int i=0; i<mTableNames.size(); i++)
	{
		command = QString("select * from %1 limit 1").arg(mTableNames[i]);
		DB.quickGet(command);
		for (int j=0; j<DB.getColCount(); j++)
		{
			QString colName = DB.getColName(j);
			QList<QTreeWidgetItem *> tableItems = ui.saveColumnNameWidget->findItems(mTableNames[i], Qt::MatchExactly);
			if (tableItems.size() > 0)
			{
				QTreeWidgetItem* tableItem = tableItems[0];
				QTreeWidgetItem* colItem = new QTreeWidgetItem(tableItem, QStringList(colName));
				colItem->setCheckState(0, Qt::Unchecked);
			}
		}
	}

	ui.saveColumnNameWidget->setHeaderHidden(true);
	ui.saveColumnNameWidget->setIndentation(10);
	ui.saveColumnNameWidget->expandAll();
}

int ExportDataDialog::exec()
{
	setExportColumnList();
	return QDialog::exec();
}

void ExportDataDialog::itemClicked(QTreeWidgetItem* item, int column)
{
	if (item->checkState(column) == Qt::Unchecked)
	{
		item->setCheckState(column, Qt::Checked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Checked);
	}
	else if (item->checkState(column) == Qt::Checked)
	{
		item->setCheckState(column, Qt::Unchecked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Unchecked);
	}
	else if (item->checkState(column) == Qt::PartiallyChecked)
	{
		item->setCheckState(column, Qt::Checked);
		for (int i=0; i<item->childCount(); i++)
			item->child(i)->setCheckState(column, Qt::Checked);
	}
	else
	{
		LOG<<"Unexpected check state"<<endl;
		assert(0);
	}

	if (item->parent())
	{
		bool allChecked=true;
		bool allUncheked=true;
		for (int i=0; i<item->parent()->childCount(); i++)
		{
			if (item->parent()->child(i)->checkState(column) != Qt::Checked)
				allChecked = false;
			if (item->parent()->child(i)->checkState(column) != Qt::Unchecked)
				allUncheked = false;
		}
		if (allChecked)
			item->parent()->setCheckState(column, Qt::Checked);
		else if(allUncheked)
			item->parent()->setCheckState(column, Qt::Unchecked);
		else
			item->parent()->setCheckState(column, Qt::PartiallyChecked);
	}

	//set default save file name
	bool saveValid=false;
	mDefaultSaveFile = OPT.getCurrendDate().toString("yyyy.MM.dd")
					+QString("_")+QTime::currentTime ().toString("hh.mm.ss");
	for (int i=0; i<ui.saveColumnNameWidget->topLevelItemCount(); i++)
	{
		if (	ui.saveColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::Checked
			||	ui.saveColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::PartiallyChecked)
		{
			mDefaultSaveFile.append(QString("_") + ui.saveColumnNameWidget->topLevelItem(i)->text(0));
			saveValid=true;
		}
	}
	mDefaultSaveFile.append(".txt");
	if (saveValid)
	{
		ui.saveFileNameEdit->setEnabled(true);
		ui.saveFileNameEdit->setText(mDefaultSaveFile);
	}
	else
	{
		ui.saveFileNameEdit->setEnabled(false);
		ui.saveFileNameEdit->clear();
	}
}

void ExportDataDialog::save()
{
	QString saveFileName = ui.saveFileNameEdit->text();
	QFile file(QString("./backup/")+saveFileName);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
		return;

	QTextStream out(&file);
	QString command;

#ifdef VERSION
	out<<"Version="<<VERSION<<endl;
#endif

	for (int i=0; i<ui.saveColumnNameWidget->topLevelItemCount(); i++)
	{
		if (	ui.saveColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::Checked
			||	ui.saveColumnNameWidget->topLevelItem(i)->checkState(0) == Qt::PartiallyChecked)
		{
			QString tableName = ui.saveColumnNameWidget->topLevelItem(i)->text(0);
			out<<"[Table]"<<tableName<<endl;
			command = QString("select ");
			for (int j=0; j<ui.saveColumnNameWidget->topLevelItem(i)->childCount(); j++)
			{
				QString colName = 	ui.saveColumnNameWidget->topLevelItem(i)->child(j)->text(0);
				command.append(colName + QString(","));
			}
			command.remove(command.lastIndexOf(','), 1);
			command.append(QString(" from %1;").arg(tableName));
			DB.quickGet(command);

			QVector<QString> colNames;
			for (int j=0; j<DB.getColCount(); j++)
			{
				out<<DB.getColName(j)<<"<sep>";
				colNames.push_back(DB.getColName(j));
			}
			out<<endl;

			for (int j=0; j<DB.getRowCount(); j++)
			{
				for (int k=0; k<colNames.size(); k++)
				{
					if (!DB.getTableValue(j, colNames[k]).isEmpty())
						out<<DB.getTableValue(j, colNames[k])<<"<sep>";
					else
						out<<"<NULL><sep>";
				}
				out<<endl;
			}
		}
	}

	this->accept();
}

